package org.wevil.service.sys;

import org.wevil.props.WxProp;
import org.wevil.dto.WxOpenIdResult;
import org.wevil.util.HttpUtil;
import org.wevil.vo.wx.WxVo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;

@Transactional
@Service
public class WxService {

    @Resource
    private WxProp wxProp;

    /** 获取openid和sessionKey */
    public WxVo getOpenId(String code) {
        String appId = wxProp.getAppId();
        String secret = wxProp.getSecret();
//        String accessTokenUri = wxProp.getAccessTokenUri();
        String openidUri = wxProp.getOpenidUri();
        String url = "https://api.weixin.qq.com" + String.format(openidUri, appId, secret, code);
        String result = HttpUtil.doGet(url, "UTF-8", null);
        WxOpenIdResult bean = JSONObject.parseObject(result, WxOpenIdResult.class);
        WxVo vo = WxVo.result2vo(bean);
        if (bean.getErrcode() != 0){
            System.out.println("微信接口[" + openidUri + "]调用异常。错误代码：" + bean.getErrcode() + "错误信息：" + bean.getErrcode());
            return null;
        }else {
            // openid 一般情况下需要持久化。保存在服务器（数据库）
            return vo;
        }
    }
}
